package topsun.rms.services;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;
import org.springframework.stereotype.Service;

import topsun.framework.utility.HqlFilter;
import topsun.rms.dao.IBaseDao;
import topsun.rms.entity.User;
import topsun.rms.entity.UserRole;

/**
 * 自定义服务类
 * 
 * @author yuxiaobei
 *
 */
@Service("customService")
//@Transactional  
public class CustomService extends BaseService<User> implements ICustomService
{
	@Resource(name = "customDao")  
	public void setDao(IBaseDao<User> dao) 
	{  
		super.setDao(dao);  
	}
	
	@Resource(name = "userRoleDao")  
	private IBaseDao<UserRole> roleDao;

	@Override
	public void grantRole(String id, String roleIds) 
	{
		User user = getById(id);
		if (user != null) 
		{
			for (String roleId : roleIds.split(",")) 
			{
				if (StringUtils.isBlank(roleId))  continue;
				
				UserRole role = roleDao.getById(roleId);
				if (role != null)
				{
					user.getUserroles().add(role);
				}
			}
			super.save(user);
		}
		
	}
	
	@Override
	public void deleteRole(String id,String roleIds)
	{
		User user = getById(id);
		if(user != null)
		{
			for(String roleId :roleIds.split(",") )
			{
				if (StringUtils.isBlank(roleId))  continue;
				
				UserRole role = roleDao.getById(roleId);
				if (role != null)
				{
					user.getUserroles().remove(role);
				}
			}
			super.save(user);
		}
	}
	
	/**
	 * 解决更新删除关联问题
	 */
	@Override
	public void update(User user)
	{
		User tuser = getById(user.getId());
		Hibernate.initialize(tuser.getLoginaccounts());
		Hibernate.initialize(tuser.getUserroles());
		Hibernate.initialize(tuser.getUsergroups());
		user.setUserroles(tuser.getUserroles());
		user.setLoginaccounts(tuser.getLoginaccounts());
		user.setUsergroups(tuser.getUsergroups());
		super.merge(user);
	}

	@Override
	public List<User> findUserByFilter(HqlFilter hqlFilter) 
	{
		String hql = "select distinct t from User t join t.userroles role";
		return find(hql + hqlFilter.getWhereAndOrderHql(), hqlFilter.getParams());
	}
	
	
	@Override
	public List<User> findUserByFilterGroup (HqlFilter hqlFilter) 
	{
		String hql = "select distinct t from User t join t.usergroups usergroup";
		return find(hql + hqlFilter.getWhereAndOrderHql(), hqlFilter.getParams());
	}
	
	@Override
	public User findUserByLoginAccountFilter(HqlFilter hqlFilter) 
	{
		String hql = "select distinct t from User t join t.loginaccounts loginaccount";
		List<User> users = find(hql + hqlFilter.getWhereAndOrderHql(), hqlFilter.getParams());
		
		return users.size() > 0 ? users.get(0) : null;
	}
}
